package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreFetcherUtils;
import com.lehecai.core.util.CoreStringUtils;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;

import java.util.*;

/**
 * 幸运农场（重庆快乐十分）官网抓取器
 * Created by zhangzq on 14-7-18.
 */
public class LotteryDrawFetch566WorkerOfficial extends AbstractLotteryDrawFetchWorker {

    private static final String RESULT_LOCALITY_URL = " http://www.16cp.com/ajaxHTTP/gamedraw/GetOpenNumber.aspx";
    private static final String PASSWORD_URL = "http://www.16cp.com/ajaxHTTP/GetUserInfo.aspx?rd=" + Math.random();
    private static final String BASE_URL = "http://www.16cp.com/gamedraw/lucky/open.shtml";

    public LotteryDrawFetch566WorkerOfficial(LotteryType lotteryType) {
        super(lotteryType);
    }
    @Override
    public LotteryDraw fetchResult(String phase) {
        return this.fetchResultDetail(phase);
    }

    @Override
    public LotteryDraw fetchResultDetail(String phase) {
        LotteryType lotteryType = this.getLotteryType();
        String url = RESULT_LOCALITY_URL;
        String pageInfo = "列表页面" + url;
        String logHeader = "==" + pageInfo + "==抓取==" + lotteryType.getName() + "==";
        logger.info(logHeader + "开始==");

        String data;
        Parser parser;
        LotteryDraw lotteryDraw = new LotteryDraw();

        Map<String, String> headerParams = new HashMap<String, String>();
        headerParams.put("Referer", BASE_URL);
        headerParams.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36");
        headerParams.put("Content-Type","application/x-www-form-urlencoded");
        try {
            //获取登录密码
            Map<String, String> getUserInfoBodyParams = new HashMap<String, String>();
            getUserInfoBodyParams.put("sType", "md5");
            data = CoreFetcherUtils.URLPostWithHeaderAndBodyParams(PASSWORD_URL, headerParams, getUserInfoBodyParams, null, CharsetConstant.CHARSET_GBK);
            logger.info("获取到模拟登录的密码: " + data);
            if (StringUtils.isEmpty(data) || data.indexOf("404 Not Found") > 0) {
                logger.error(logHeader + "data is null or 404 Not Found");
                logger.error("未获取到模拟登录的密码！");
                return null;
            }
            //默认登录获取开奖信息列表
            Map<String, String> getResultBodyParams = new HashMap<String, String>();
            getResultBodyParams.put("sPass",data);
            getResultBodyParams.put("idMode","9");
            getResultBodyParams.put("iType","2");
            getResultBodyParams.put("iCount","1");
            //获取开奖信息
            data = CoreFetcherUtils.URLPostWithHeaderAndBodyParams(RESULT_LOCALITY_URL, headerParams, getResultBodyParams, null, CharsetConstant.CHARSET_GBK);
            if (StringUtils.isEmpty(data) || data.indexOf("404 Not Found") > 0) {
                logger.error(logHeader + "data is null or 404 Not Found");
                logger.error("未获取到开奖详情信息列表！");
                return null;
            }
            parser = Parser.createParser(data, CharsetConstant.CHARSET_GBK);
            NodeList tableNodeList;
            try {
                NodeFilter tableFilter = new TagNameFilter("table");
                NodeFilter cssFilter = new HasAttributeFilter("style", "background-color: #b8b8b8;");
                NodeFilter filter = new AndFilter(tableFilter, cssFilter);
                tableNodeList = parser.extractAllNodesThatMatch(filter);
            } catch (Exception e) {
                logger.error(logHeader + "数据解析错误==" + e.getMessage(), e);
                return null;
            }
            String lotteryPhase;
            String timeDraw;
            String result;

            //如果传入的彩期为null 则默认取最新一期的数据
            boolean isCurrentPhase = false;
            if (StringUtils.isEmpty(phase)) {
                isCurrentPhase = true;
            }
            if (tableNodeList != null && tableNodeList.size() > 0) {
                TableTag tableTag = (TableTag)tableNodeList.elementAt(0);
                if (tableTag == null || tableTag.getRowCount() < 1) {
                    logger.error("未获取到开奖详情信息列表！");
                    return null;
                }
                for (int i = 1; i < tableTag.getRowCount(); i++) {
                    TableColumn[] tableColumn = tableTag.getRow(i).getColumns();
                    lotteryPhase = CoreStringUtils.trimAll(tableColumn[0].toPlainTextString());
                    if (StringUtils.isNotEmpty(lotteryPhase) && lotteryPhase.length() > 10) {
                        lotteryPhase = lotteryPhase.substring(2);
                    }
                    if (isCurrentPhase || phase.equals(lotteryPhase)) {
                        String resultTemp = tableColumn[1].toPlainTextString().replace("&nbsp;", " ").replace("  ", " ");
                        String[] resultArray = resultTemp.split(" ");
                        result = CoreFetcherUtils.mergeStringArray(resultArray, ",");
                        timeDraw = tableColumn[7].toPlainTextString().replace("&nbsp;", " ");
                        if (StringUtils.isNotEmpty(timeDraw) && timeDraw.length() < 17) {
                            timeDraw = timeDraw + ":00";
                        }
                        lotteryDraw.setPhase(lotteryPhase);
                        lotteryDraw.setResult(result);
                        lotteryDraw.setTimeDraw(timeDraw);
                        lotteryDraw.setLotteryType(getLotteryType());
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取开奖详情出现异常");
            logger.error(e.getMessage(), e);
        }
        if (lotteryDraw.getResult() == null) {
            logger.error(logHeader + "未获取到开奖详情信息，可能开奖详情信息已超出第一页 或者 官网尚未及时更新开奖信息！");
            return null;
        }
        logger.info(logHeader + "结束");
        return lotteryDraw;
    }

    @Override
    protected String getResultDetailUrl(String phase) {
        return null;
    }

    @Override
    protected String getResultUrl(String phase) {
        return null;
    }
}
